import React, { useEffect, useRef, useState } from 'react'
import { Button } from 'antd'
import { ProTable, BetaSchemaForm } from '@ant-design/pro-components'
import TableComulnUtil from './utils/TableComulnUtil'
import FormComulnUtil from './utils/FormComulnUtil'
import { PlusOutlined } from '@ant-design/icons'
import { Dialog, Notification } from '@alifd/next'
import MonacoEditor, { loader } from '@monaco-editor/react'

loader.config({ paths: { vs: "/monaco-editor@0.30.1/min/vs" } });

export default React.memo((props) => {
  const [tableColumns, setTableColumns] = useState([])
  const [idField, setIdField] = useState('id')
  const [reset, setReset] = useState(false)
  const ref = useRef()

  let dialog = null
  useEffect(()=>{ init() }, [props])

  const getRequestUrl =  () => {
    return window.LOW_CODE_REQUEST_API || `/api/db.table/${props.table}`
  }

  const init = async() => {
    setIdField(props.config.primary)
    const tableColumns = TableComulnUtil(props)
    if(props.auths.EDIT || props.auths.DELETE || props.auths.DETAIL){
      tableColumns.push({
        title: '操作',
        valueType: 'option',
        key: 'option',
        render: (text, record, _, action) => {
          const option = []
          if(props.auths.DETAIL){ option.push(<a key="detail" onClick={()=>onDetail(record)}>查看</a>) }
          if(props.auths.EDIT){ option.push(<a key="editable" onClick={()=>onEdit(record)}>编辑</a>) }
          if(props.auths.DELETE){ option.push(<a key="delete" onClick={()=>onDelete(record)}>删除</a>) }
          return option
        }
      })
    }
    setTableColumns(tableColumns)
    if(props.option == 'DETAIL'){
      const row = await request.get(`${getRequestUrl()}/${props.id}`)
      if(row){
        onDetail(row)
        return
      }
      Notification.error({ title: `没有找到数据${props.id}` })
    }
  }

  const req = async(req = {}, _sort) => {
    const filter = {
      ...(props.config?.default?.filters || {}),
      ...req
    }
    if(props.option == 'DETAIL' && !reset){
      filter.id = props.id
    }
    delete filter.current
    delete filter.pageSize
    const sort = Object.keys(_sort).map(key=>{
      return key.indexOf('.') == -1 ? `${props.table}.${key} ${_sort[key] == 'ascend' ? ' ASC' : ' DESC'}` :`${key} ${_sort[key] == 'ascend' ? ' ASC' : ' DESC'}`
    })
    const data = await request.post(getRequestUrl(), { page: req.current, pageSize: 5, filter, sort:[...sort, ...(props.config?.default?.sort || [])] })
    return { data: data.data, success: true, total: data.count }
  }

  const onAdd = () => {
    if(props.onAdd){
      addTab(props.onDetail, {type : 'ADD', data:{}})
      return
    }
    const formColumns = FormComulnUtil(props, true)
    const form = <BetaSchemaForm layoutType="Form" rowProps={{ gutter: [16, 16] }} colProps={{ span: 12 }} grid={true} searchConfig={props.config.buttons} onFinish={form=>{ onFinish('ADD', {}, form) }} columns={formColumns}/>
    dialog = Dialog.show({ title: `新增${props.config.comment}`, width:'800px', v2: true, hasMask: true, footer: false, content: form})
  }

  const onDetail = (row) => {
    if(props.onDetail){
      addTab(props.onDetail, {type : 'DETAIL', data:row})
      return
    }
    const formColumns = FormComulnUtil(props, false)
    const form = <BetaSchemaForm submitter={false} layoutType="Form" initialValues={row} rowProps={{ gutter: [16, 16] }} colProps={{ span: 12 }} grid={true} searchConfig={props.config.buttons} onFinish={form=>{ onFinish('DETAIL', row, form) }} columns={formColumns}/>
    dialog = Dialog.show({ title: `${props.config.comment}详情`, width:'800px', v2: true, hasMask: true, footer: false, content: form})
  }

  window.onDetail = onDetail

  const onEdit = (row) => {
    if(props.onEdit){
      addTab(props.onDetail, {type : 'EDIT', data:row})
      return
    }
    const formColumns = FormComulnUtil(props, true)
    const form = <BetaSchemaForm layoutType="Form" initialValues={row} rowProps={{ gutter: [16, 16] }} colProps={{ span: 12 }} grid={true} searchConfig={props.config.buttons} onFinish={form=>{ onFinish('EDIT', row, form) }} columns={formColumns}/>
    dialog = Dialog.show({ title: `编辑${props.config.comment}`, width:'800px', v2: true, hasMask: true, footer: false, content: form})
  }

  const onDelete = (row) => { }

  const onFinish = async(TYPE, row, values) => {
    const form = <div style={{height:"340px"}}><MonacoEditor defaultValue={JSON.stringify(values, null, '\t')} theme="vs-dark" defaultLanguage="json" options={{selectOnLineNumbers:true}} width='100%' height='330px' /></div>
    Dialog.show({ title: `提交数据内容`, width:'800px', v2: true, hasMask: true, footer: false, content: form})
    ref.current.reload()
    dialog && dialog.hide()
  }

  return (
    <ProTable actionRef={ref} toolbar={{title: props.config.comment}} scroll={{x:true}} cardBordered rowKey={idField} columns={tableColumns} 
      toolBarRender={()=>props.auths.ADD ? [<Button key="button" icon={<PlusOutlined />} onClick={onAdd} type="primary">新建</Button>] : []}
      pagination={{ pageSize: 5 }} request={req} onReset={()=>{ setReset(true) }}/>
  )
})